package cn.iocoder.yudao.module.brokerage.record.dao;

import cn.iocoder.yudao.framework.business.basic.dao.mapper.CoreMapper;
import cn.iocoder.yudao.framework.business.basic.dao.query.CoreLambdaQueryWrapper;
import cn.iocoder.yudao.module.brokerage.record.pojo.bo.BrokerageRecordMonthSummaryBO;
import cn.iocoder.yudao.module.brokerage.record.pojo.po.BrokerageRecordDO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 推广用户分佣记录 Mapper
 *
 * @author 山野羡民
 */
@Mapper
public interface BrokerageRecordMapper extends CoreMapper<BrokerageRecordDO> {

    default List<BrokerageRecordDO> selectListByStatusAndLessThanUnfreezeTime(Integer status, LocalDateTime unfreezeTime) {
        return selectList(new LambdaQueryWrapper<BrokerageRecordDO>()
                .eq(BrokerageRecordDO::getStatus, status)
                .lt(BrokerageRecordDO::getUnfreezeTime, unfreezeTime));
    }

    default int updateByIdAndStatus(Long id, Integer status, BrokerageRecordDO updateObj) {
        return update(updateObj, new LambdaQueryWrapper<BrokerageRecordDO>()
                .eq(BrokerageRecordDO::getId, id)
                .eq(BrokerageRecordDO::getStatus, status));
    }

    default List<BrokerageRecordDO> selectByBizTypeAndBizId(String bizType, String bizId) {
        return selectList(new CoreLambdaQueryWrapper<BrokerageRecordDO>()
                .eq(BrokerageRecordDO::getBizType, bizType)
                // 购买产品的情况，bizId为 tradeNo+@+orderItemId，如：TRD202504211051561@1914150078111678465。
                // 通过 tradeNo 或 orderItemId 查询会有多条数据。
                .like(BrokerageRecordDO::getBizId, bizId));
    }

    @Select("""
            SELECT IFNULL(SUM(bonus_money),0) AS total_money
            FROM brokerage_record
            WHERE deleted = FALSE
            AND user_id = #{userId}
            AND status = #{status}
            AND YEAR(create_time) = #{year}
            AND MONTH(create_time) = #{month}
            """)
    int selectMoneySum(@Param("userId") Long userId, @Param("year") int year, @Param("month") int month, @Param("status") Integer status);

    @Select("""
            SELECT SUM(bonus_money) AS total_money, YEAR(create_time) AS year, MONTH(create_time) AS month
            FROM brokerage_record
            WHERE user_id = #{userId}
            AND status = #{status}
            AND create_time >= DATE_SUB(CURDATE(), INTERVAL #{limitMonth} MONTH)
            GROUP BY year, month
            ORDER BY year DESC, month DESC
            """)
    List<BrokerageRecordMonthSummaryBO> selectMoneySums(@Param("userId") Long userId, @Param("status") Integer status, @Param("limitMonth") int limitMonth);

}